package com.mes.web.controller.tdd;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.mes.entity.tdd.ProcurementChuku;
import com.mes.entity.tdd.ProcurementChukuMateriel;
import com.mes.entity.tdd.ProcurementRukuMateriel;
import com.mes.entity.tdd.tj.Tpage;
import com.mes.service.tdd.ProcurementChukuMaterielService;
import com.mes.service.tdd.ProcurementChukuService;
import com.mes.service.tdd.ProcurementRukuMaterielService;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ExcelUtils;
import com.mes.utils.ResponseUtil;
import com.mes.utils.StringUtil;
/**
 * 
 *@ClassName: ProcurementChukuController 
 *@Description: 采购退货
 *@Author tdd
 *@Date 2018-6-5 下午3:29:24 
 *@version 1.0
 */
@Controller
@RequestMapping("/procurementChuku")
public class ProcurementChukuController {
	//注入退货单Server
	@Resource public ProcurementChukuService chukuService;
	//注入退货单详情Server
	@Resource public ProcurementChukuMaterielService chukuMaterielService;
	//注入到货单详情Server
	@Resource public ProcurementRukuMaterielService rukuMaterielService;
	/**
	 * 退货单分页
	 * @param request request对象
	 * @param pageBean 分页+条件
	 * @param limit 每页条数
	 * @param offset 条数
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/list")
	public void materieDemandList(HttpServletRequest request,Tpage pageBean,@RequestParam(value="limit",required=false)String limit,@RequestParam(value="offset",required=false)String offset,HttpServletResponse response) throws Exception {
		/*String suppliername = request.getParameter("suppliername"); 
		if(null != suppliername && !suppliername.equals("")){
			suppliername = new String(suppliername.getBytes("iso8859-1"),"utf-8");
			pageBean.setStaffname(suppliername);
		}*/
		//页数
		pageBean.setPage(Integer.parseInt(offset)/Integer.parseInt(limit));
		//每页条数
		pageBean.setPageSize(Integer.parseInt(limit));
		//未删除
		pageBean.setIsdelete("0");
		List<ProcurementChuku> list=chukuService.list(pageBean);
		int total=chukuService.total(pageBean);
		
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}
	/**
	 * 根据退货单号查退货单
	 * @param pcnum 退货单号
	 * @return 退货单集合
	 */
	public List<ProcurementChuku> findbypcnum(String pcnum){
		Tpage pageBean = new Tpage();
		//未删除
		pageBean.setIsdelete("0");
		pageBean.setPcnum(pcnum);
		//页数
		pageBean.setPage(0);
		//每页条数
		pageBean.setPageSize(chukuService.total(pageBean));
		List<ProcurementChuku> list=chukuService.list(pageBean);
		return list;
	}
	/**
	 * 根据到货单id查 到货单+物料
	 * @param prukuid 到货单id
	 * @return 到货单详情集合
	 */
	public List<ProcurementRukuMateriel> findbyprukuid(String prukuid){
		Tpage pageBean = new Tpage();
		//未删除
		pageBean.setPrid(Long.valueOf(prukuid));
		//每页条数
		int total=rukuMaterielService.total(pageBean);
		//页数
		pageBean.setPage(0);
		pageBean.setPageSize(total);
		List<ProcurementRukuMateriel> list = rukuMaterielService.list(pageBean);
		return list;
	}
	/**
	 * 添加退货单
	 * @param procurementChuku 退货单
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/add")
	public void materieDemandAdd(ProcurementChuku procurementChuku,HttpServletResponse response) throws Exception {
		List<ProcurementChuku> findbypcnum = findbypcnum(procurementChuku.getPcnum());
		Gson gson = new Gson();
		Map<String,Object> map=new HashMap<String,Object>();
		if (null != findbypcnum && findbypcnum.size() > 0) {
			map.put("success", "-1");
		}else {
			//未退货
			procurementChuku.setPcstate("0");
			//未审批
			procurementChuku.setPcapprovalstate("0");
			
			Long id = chukuService.add(procurementChuku);
			if (null != id && id > 0) {
				/*根据到货单id查 到货单+物料*/
				List<ProcurementRukuMateriel> findbyprukuid = findbyprukuid(procurementChuku.getPrukuid());
				for (ProcurementRukuMateriel rukuMateriel : findbyprukuid) {
					ProcurementChukuMateriel chukuMateriel = new ProcurementChukuMateriel();
					chukuMateriel.setPcid(id);
					chukuMateriel.setMaterielid(rukuMateriel.getMaterielid());
					chukuMateriel.setPcmremark1(rukuMateriel.getPmbatchnumber());
					chukuMateriel.setPcmremark2(rukuMateriel.getBarcode());
					chukuMateriel.setNumber(rukuMateriel.getNumber());
					//添加
			    	chukuMaterielService.add(chukuMateriel);
				}
				map.put("success", "1");
				map.put("pcid", id);
			}else {
				map.put("success", "0");
			}
		}
		ResponseUtil.write(response, gson.toJson(map));
	}
	/**
	 * 去修改退货单
	 * @param model map集合
	 * @param request request对象
	 * @return 跳转tdd/erp/procurementChukuAdd.jsp
	 */
	@RequestMapping("/toupdata")
	public String toupdata(Model model,HttpServletRequest request){
		Tpage pageBean = new Tpage();
		//页数
		pageBean.setPage(0);
		//每页条数
		pageBean.setPageSize(10);
		pageBean.setPcid(Long.valueOf((Integer.parseInt(request.getParameter("pcid")))));
		List<ProcurementChuku> list = chukuService.list(pageBean);
		if (list.size()>0) {
			model.addAttribute("procurementChuku", list.get(0));
		}
		return "tdd/erp/procurementChukuAdd";
	}
	/**
	 * 修改退货单
	 * @param procurementChuku 退货单
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/save")
	public void materieDemandSave(ProcurementChuku procurementChuku,HttpServletResponse response) throws Exception {
		Tpage pageBean = new Tpage();
		//页数
		pageBean.setPage(0);
		//每页条数
		pageBean.setPageSize(10);
		pageBean.setPcid(procurementChuku.getPcid());
		List<ProcurementChuku> list = chukuService.list(pageBean);
		Map<String,Object> map=new HashMap<String,Object>();
		Gson gson = new Gson();
		if (list.size() > 0) {
			List<ProcurementChuku> findbypcnum = findbypcnum(procurementChuku.getPcnum());
			if (null != findbypcnum && findbypcnum.size() > 0 && !procurementChuku.getPcid().equals(findbypcnum.get(0).getPcid())) {
				map.put("success", "-1");
			}else {
				int id = chukuService.updata(procurementChuku);
				if ( id > 0) {
					map.put("success", "1");
				}else {
					map.put("success", "0");
				}
			}
		//已删除
		} else {
			map.put("success", "2");
		}
		ResponseUtil.write(response, gson.toJson(map));
	}
	/**
	 * 采购退货单2
	 * @param procurementChuku 退货单
	 * @param response  response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/save1")
	public void materieDemandSave1(ProcurementChuku procurementChuku,HttpServletResponse response) throws Exception {
		Tpage pageBean = new Tpage();
		//页数
		pageBean.setPage(0);
		//每页条数
		pageBean.setPageSize(10);
		pageBean.setPcid(procurementChuku.getPcid());
		List<ProcurementChuku> list = chukuService.list(pageBean);
		//Map<String,Object> map=new HashMap<String,Object>();
		Gson gson = new Gson();
		if (list.size() > 0) {
			ProcurementChuku procurementChuku2=list.get(0);
			procurementChuku2.setPcstate(procurementChuku.getPcstate());
			int id = chukuService.updata(procurementChuku2);
			if ( id > 0) {
				//map.put("success", "1");
				response.getWriter().print("1");
			}else {
				//map.put("success", "0");
				response.getWriter().print("0");
			}
		
			//已删除
		} else {
			//map.put("success", "2");
			response.getWriter().print("2");
		}
		//ResponseUtil.write(response, gson.toJson(map));
	}
	/**
	 * 删除退货单
	 * @param ids 以","拼接退货单id组成字符串
	 * @param response  response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/delete")
	public void materieDemandDelete(String ids,HttpServletResponse response) throws Exception {
		List<Long> listId = StringUtil.splitListL(ids, ",");
        for (int i = 0; i < listId.size(); i++) {
			Tpage pageBean = new Tpage();
			//页数
			pageBean.setPage(0);
			//每页条数
			pageBean.setPageSize(10);
			pageBean.setPcid(listId.get(i));
			List<ProcurementChuku> list = chukuService.list(pageBean);
			if (list.size() > 0) {
				ProcurementChuku procurementChuku = list.get(0);
        		//是否删除指定删除
        		//删除（假删除）
        		int n = chukuService.updatadelete(procurementChuku);
        		//删除成功
        		if (n >= 1) {
        			Tpage  tpage = new Tpage();
    				tpage.setPcid(listId.get(i));
    				//页数
    				pageBean.setPage(0);
    				//每页条数
    				pageBean.setPageSize(chukuMaterielService.total(tpage));
    				List<ProcurementChukuMateriel> listM = chukuMaterielService.list(tpage);
    				for (ProcurementChukuMateriel chukuMateriel : listM) {
    					//删除
    					chukuMaterielService.updatadelete(chukuMateriel);
					}
        			if (i == (listId.size()-1)) {
        				response.getWriter().print("1");
					}
        			//未成功
        		} else {
        			response.getWriter().print("0");
        			continue;
        		}
        	//如果没有该条数据(没有)
			} else {
				//该数据不存在
        		response.getWriter().print("2");
        		continue;
			}
        }
	}
	/**
	 * 导出数据
	 * @param pageBean 条件+分页
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/doExport")
	public void doExport(Tpage pageBean,HttpServletResponse response) throws Exception {
		//页数
		pageBean.setPage(0);
		//每页条数
		pageBean.setPageSize(chukuService.total(pageBean));
		List<ProcurementChuku> chukus=chukuService.list(pageBean);
		List<List<String>> lists = chukuzhuanlist(chukus);
		ExcelUtils.export("员工当前数据",namess(), response,lists );
	}
	/**
	 * 根据导出数据表头把List<ProcurementChuku>转List<List<String>>
	 * @param chukus 出库单集合
	 * @return 字符串双集合
	 */
	public List<List<String>> chukuzhuanlist (List<ProcurementChuku> chukus){
		List<List<String>> lists = new ArrayList<>();
		for (ProcurementChuku chuku : chukus) {
			List<String> list = new ArrayList<>();
			list.add(chuku.getPcnum());
			list.add(chuku.getPcdate());
			list.add(chuku.getSupplier().getSuppliername());
			if(chuku.getPcstate() == "0"){
				list.add("未退货");
			}else if(chuku.getPcstate() =="1"){
				list.add("已退货");
			}else{
				list.add("");
			} 
			if(chuku.getPcapprovalstate() == "0"){
				list.add("未审批");
			}else if(chuku.getPcapprovalstate() =="1"){
				list.add("已审批");
			}else{
				list.add("");
			} 
			lists.add(list);
			list = null;
		}
		return lists;
	}
	
	/**
	 * 导出数据表头
	 * @return 表头字符串集合
	 */
	public List<String> namess(){
		List<String> list = new ArrayList<>();
		list.add("退货编号");
		list.add("退货日期");
		list.add("供应商");
		list.add("状态");
		list.add("审批状态");
		return list;
	}
	
	
	
	/**
	 * 一步添加
	 * @param procurementChuku 单
	 * @param pmid 到货单详情id
	 * @param materielid 物料id
	 * @param pmbatchnumber 批号
	 * @param barcode 条形码
	 * @param number 数量
	 * @param tuireason 原因
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/addBack")
	public void addBack(ProcurementChuku procurementChuku,String[] pmid,String[] materielid,String[] pmbatchnumber,String[] barcode,String[] number,String[] tuireason,HttpServletResponse response) throws Exception {
		List<ProcurementChuku> findbypcnum = findbypcnum(procurementChuku.getPcnum());
		Gson gson = new Gson();
		Map<String,Object> map=new HashMap<String,Object>();
		if (null != findbypcnum && findbypcnum.size() > 0) {
			map.put("success", "-1");
		}else {
			//未退货
			procurementChuku.setPcstate("0");
			//未审批
			procurementChuku.setPcapprovalstate("0");
			
			Long id = chukuService.add(procurementChuku);
			if (null != id && id > 0) {
				/*根据到货单id查 到货单+物料*/
				for (int i = 0; i < pmid.length; i++) {
					ProcurementChukuMateriel chukuMateriel = new ProcurementChukuMateriel();
					chukuMateriel.setPcid(id);
					chukuMateriel.setMaterielid(Long.valueOf(materielid[i]));
					chukuMateriel.setPcmremark1(pmbatchnumber[i]);
					chukuMateriel.setPcmremark2(barcode[i]);
					chukuMateriel.setNumber(number[i]);
					chukuMateriel.setTuireason(tuireason[i]);
					//添加
			    	chukuMaterielService.add(chukuMateriel);
				}
				map.put("success", "1");
				map.put("pcid", id);
			}else {
				map.put("success", "0");
			}
		}
		ResponseUtil.write(response, gson.toJson(map));
	}
	
	
	
	/**
	 * 一步修改
	 * @param procurementChuku 单
	 * @param pcmid 详情id
	 * @param number 数量
	 * @param tuireason 退货原因
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/saveBack")
	public void saveBack(ProcurementChuku procurementChuku,String[] pcmid,String[] number,String[] tuireason,HttpServletResponse response) throws Exception {
		Tpage pageBean = new Tpage();
		//页数
		pageBean.setPage(0);
		//每页条数
		pageBean.setPageSize(10);
		pageBean.setPcid(procurementChuku.getPcid());
		List<ProcurementChuku> list = chukuService.list(pageBean);
		Map<String,Object> map=new HashMap<String,Object>();
		Gson gson = new Gson();
		if (list.size() > 0) {
			List<ProcurementChuku> findbypcnum = findbypcnum(procurementChuku.getPcnum());
			if (null != findbypcnum && findbypcnum.size() > 0 && !procurementChuku.getPcid().equals(findbypcnum.get(0).getPcid())) {
				map.put("success", "-1");
			}else {
				int id = chukuService.updata(procurementChuku);
				if ( id > 0) {
					/*添加到货单详情*/
					for (int i = 0; i < pcmid.length; i++) {
						//根据id查数据
				        //修改前数据
				    	Tpage pageBean1 = new Tpage();
						//获取id
						pageBean1.setPcmid(Long.valueOf(pcmid[i]));
						//页数
						pageBean1.setPage(0);
						//每页条数
						pageBean1.setPageSize(10);
						List<ProcurementChukuMateriel> listm = chukuMaterielService.list(pageBean1);
						//如果有该条数据
						if (listm.size()>0) {
							ProcurementChukuMateriel cm2 = listm.get(0);
							if( null!= number[i] && !number[i].equals("")){
								cm2.setNumber(number[i]);
							}
							if( null!= tuireason[i] && !tuireason[i].equals("")){
								cm2.setTuireason(tuireason[i]);
							}
				        	//修改
							int n = chukuMaterielService.updata(cm2);
						}
					}
					map.put("success", "1");
				}else {
					map.put("success", "0");
				}
			}
		//已删除
		} else {
			map.put("success", "2");
		}
		ResponseUtil.write(response, gson.toJson(map));
	}
}
